<template>
  <div class="app-container">
    <u-page title="主题管理">
      <div slot="header">
        <el-button type="primary" icon="el-icon-plus" @click="hdlOpen()">
          {{ textMap['create'] }}
        </el-button>
      </div>
      <u-filtered>
        <el-form :inline="true" :model="listQuery" class="search-form">
          <el-form-item label="主题名称" prop="name">
            <el-input v-model="listQuery.name" placeholder="请输入主题名称" clearable style="width: 170px" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="hdlFilter">搜索</el-button>
          </el-form-item>
        </el-form>
      </u-filtered>

      <u-table
        :data="list"
        :loading="listLoading"
        :options="listOptions"
        :columns="columns"
        :pagination.sync="listQuery"
        :fetch="hdlList"
        @selection-change="hdlSelectChange"
      >
        <template v-slot:right>
          <el-table-column label="操作" align="center" fixed="right">
            <template slot-scope="{ row }">
              <el-button type="text" @click="handleEdit(row)">编辑</el-button>
              <el-button type="text" @click="downLoadQrCode(row)">下载专区二维码</el-button>
<!--              <el-dropdown-item @click.native="downLoadQrCode(row)">下载专区二维码</el-dropdown-item>-->
              <el-button type="text" @click="hdlDelete(row.id, row.name)">删除</el-button>
            </template>
          </el-table-column>
        </template>
      </u-table>
    </u-page>
    <u-dialog :title="textMap[dialogStatus]" :show.sync="dialogFormVisible" width="980px" @confirm="dialogStatus==='create'? handleCreate():handleUpdate()">
      <el-form ref="dialogForm" :model="dataForm" :rules="rules" label-width="100px">
        <el-form-item label="活动时间" prop="validityDate">
          <u-date-time-picker v-model="dataForm.validityDate" value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%" />
        </el-form-item>

        <el-form-item label="主题名称" prop="name">
          <el-input v-model="dataForm.name" maxlength="20" placeholder="请输入活动名称" clearable style="width: 100%" />
        </el-form-item>
<!--        <el-form-item prop="pic" label="主题图片">-->
<!--          <u-upload v-model="dataForm.pic" name="file" tips="主题图片 尺寸比例750*300" />-->
<!--        </el-form-item>-->

        <el-form-item>
          <div style="text-align: right">
            <el-button type="primary" icon="el-icon-plus" @click="addCoupon">
              添加卡券商品
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="卡券列表" prop="coupons">

          <el-table :data="selectedCoupons" border>
            <el-table-column prop="goodsNo" label="卡券编号" />
            <el-table-column prop="goodsName" label="卡券名称" />
            <el-table-column label="操作" align="center" fixed="right">
              <template slot-scope="{ row }">
                <el-button type="text" @click="hdlDeleteCoupon(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="dataForm.status">
            <el-radio :label="true">启用</el-radio>
            <el-radio :label="false">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="location" label="排序">
          <el-input v-model="dataForm.location" placeholder="数字越大，排名越靠前" clearable />
        </el-form-item>
      </el-form>
    </u-dialog>

    <el-dialog
      title="添加卡券商品"
      :visible.sync="dialogFormConponVisible"
    >
      <el-form :inline="true" :model="conponListQuery" class="search-form">
        <el-form-item label="商品分类" prop="categoryId">
          <goods-category v-model="conponListQuery.categoryId" />
        </el-form-item>
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="conponListQuery.goodsName" placeholder="关键词搜索" clearable />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="conponListQuery.state" placeholder="请选择状态" class="state" clearable>
            <el-option value="" label="全部" />
            <el-option :value="1" label="上架" />
            <el-option :value="2" label="下架" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态" prop="auditState">
          <el-select v-model="conponListQuery.auditState" placeholder="请选择状态" class="state" clearable>
            <el-option value="" label="全部" />
            <el-option :value="1" label="待审核" />
            <el-option :value="2" label="已审核" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="hdConponList">查询</el-button>
        </el-form-item>

      </el-form>
      <u-table
        index="index"
        :data="couponlist"
        :loading="listLoading"
        :options="listOptions"
        :columns="couponColumns"
        :pagination.sync="conponListQuery"
        @selection-change="hdlSelectChange"
      >
        <template v-slot:right>
          <el-table-column label="操作" align="center" fixed="right">
            <template slot-scope="{ row }">
              <el-button v-if="isSelected(row)" @click="add(row)">选择</el-button>
              <el-button v-else type="primary" @click="sub(row)">已选</el-button>
            </template>
          </el-table-column>
        </template>
      </u-table>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogFormConponVisible = false">取 消</el-button>
        <el-button type="primary" @click="hdSure">确 定</el-button>
      </span>

    </el-dialog>

  </div>
</template>

<script>
import { saveAs } from 'file-saver'
import GoodsCategory from '@/views/plugins/couponmall/components/GoodsCategory.vue'
import axios from 'axios'

export default {
  components: { GoodsCategory },
  data() {
    return {
      api: this.$u.api.PluginsCouponmallSchedule,
      dataForm: {
        ifWhiteList: false,
        coupons: []
      },
      rules: {
        validityDate: [
          { required: true, message: '时间必选', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '主题名称必填', trigger: 'blur' }
        ],
        // pic: [
        //   { required: true, message: '主题图片未上传', trigger: 'blur' }
        // ]
      },
      listQuery: {
        page: 1,
        pageSize: 10,
        totalCount: 1,
        status: true
      },

      textMap: {
        update: '编辑主题',
        create: '新建主题'
      },
      dialogFormVisible: false,
      dialogStatus: '',

      // 表格
      columns: [
        {
          prop: 'name',
          label: '主题名称'
        },

        {
          prop: 'beginDate',
          label: '开始时间'
        },
        {
          prop: 'endDate',
          label: '结束时间'
        },

        // {
        //   prop: 'pic',
        //   label: '主题图片',
        //   image: true
        // },
        {
          prop: 'status',
          label: '状态',
          render: (h, params) => {
            if (params.row.status) {
              return h('el-tag', { props: { type: 'success' }}, '已启用')
            } else {
              return h('el-tag', { props: { type: 'danger' }}, '禁用')
            }
          }
        },
        {
          prop: 'location',
          label: '排序'
        }

      ],
      listLoading: false,
      list: [],
      listOptions: {
        stripe: true
      },
      newForm: {
        type: 1,
        accType: 1,
        status: true,
        cardTypeList: ['104', '101', '102', '103'],
        blackEnable: true,
        ifWhiteList: false
      },
      dialogFormConponVisible: false,
      couponColumns: [
        {
          prop: 'category',
          label: '商品分类',
          render: (h, params) => {
            const { category } = params.row
            if (category) {
              return h('div', category.name)
            }
          }
        },
        {
          prop: 'goodsLogo',
          label: '商品LOGO',
          image: true
        },
        {
          prop: 'goodsName',
          label: '商品名称'
        },
        {
          prop: 'goodsNo',
          label: '商品编号'
        },
        {
          prop: 'state',
          label: '展示状态',
          render: (h, params) => {
            const { state } = params.row
            if (state === 2) {
              return [h('el-tag', { props: { type: 'danger' }}, '下架')]
            } else if (state === 1) {
              return [h('el-tag', { props: { type: 'success' }}, '上架')
              ]
            }
          }
        },
        {
          prop: 'onlineDate',
          label: '上架日期',
          width: '180',
          render: (h, params) => {
            let { onlineStartTime, onlineEndTime } = params.row
            if (!onlineStartTime) {
              onlineStartTime = '不限制'
            }
            if (!onlineEndTime) {
              onlineEndTime = '不限制'
            }
            return [
              h('el-tag', { props: { effect: 'plain' }}, '起始:' + onlineStartTime),
              h('br'),
              h('el-tag', { props: { effect: 'plain' }}, '终止:' + onlineEndTime)
            ]
          }
        },
        {
          prop: 'timeRangeList',
          label: '售卖时间段',
          width: '180',
          render: (h, params) => {
            let { sellStartTime, sellEndTime } = params.row
            if (!sellStartTime) {
              sellStartTime = '不限制'
            }
            if (!sellEndTime) {
              sellEndTime = '不限制'
            }
            const res = []
            const br = h('br')
            for (let i = 0; i < params.row.length; i++) {
              const start = h('el-tag', { props: { effect: 'plain' }}, '起始:' + params.row[i][0])
              const end = h('el-tag', { props: { effect: 'plain' }}, '终止:' + params.row[i][1])
              res.push(start)
              res.push(br)
              res.push(end)
              if (i !== params.row.length - 1) { res.push(br) }
            }
            return res
          }
        }

      ],
      couponlist: [],
      conponListQuery: {
        pageNumber: 1,
        pageSize: 10,
        totalCount: 1,
        beginTime: '',
        endTime: '',
        name: '',
        mobile: '',
        status: ''
      },
      selectedCoupons: []
    }
  },
  created() {
    this.hdlList()
  },
  methods: {
    downLoadQrCode(row) {
      const self = this
      const name = row.name
      return axios({
        method: 'get',
        url: 'nt/plugins/couponmall/schedule/getScheduleGoodsQrCode/' + row.id,
        responseType: 'blob'
      }).then(res => {
        const blobData = new Blob([res.data], { type: 'application/vnd.ms-excel;charset=utf-8' })
        saveAs(blobData, name + '.png')
      })
    },
    hdlDeleteCoupon(row) {
      this.selectedCoupons.splice(this.selectedCoupons.findIndex(item => item.id === row.id), 1)
    },
    hdSure() {
      this.dialogFormConponVisible = false
      this.couponlist = []
    },

    // 取消选中事件
    sub(row) {
      this.selectedCoupons.splice(this.selectedCoupons.findIndex(item => item.id === row.id), 1)
    },
    // 选中事件
    add(row) {
      this.selectedCoupons.push(row)
    },
    // 是否选中
    isSelected(row) {
      return this.$u.test.empty(this.selectedCoupons.filter(d => d.id === row.id)[0])
    },
    hdConponList() {
      const self = this
      self.$u.api.PluginsCouponmallGoods.list(self.conponListQuery).then(res => {
        // 获取列表数据
        self.couponlist = res.data.list
      })
    },
    // 打开弹窗
    addCoupon() {
      this.dialogFormConponVisible = true
      // this.hdConponList()
    },
    // 新增事件
    handleCreate() {
      const { validityDate } = this.dataForm
      if (validityDate) {
        this.dataForm.beginDate = validityDate[0]
        this.dataForm.endDate = validityDate[1]
      }
      // console.log(this.dataForm)
      this.dataForm.goodsIds = this.selectedCoupons.map(coupon => coupon.id).join(',')
      this.hdlCreate()
    },
    // 打开修改弹窗
    handleEdit(row) {
      this.$u.api.PluginsCouponmallSchedule.fetch(row.id).then(res => {
        const { beginDate, endDate, cardType, goodsList } = res.data
        row.validityDate = []
        if (beginDate && endDate) {
          row.validityDate = [beginDate, endDate]
        }
        if (cardType) {
          row.cardTypeList = cardType.split(',')
        }
        if (goodsList) {
          this.selectedCoupons = goodsList
        }
        this.hdlEdit(row)
      })
    },
    // 更新操作
    handleUpdate() {
      const { validityDate } = this.dataForm
      if (validityDate) {
        this.dataForm.beginDate = validityDate[0]
        this.dataForm.endDate = validityDate[1]
      }
      this.dataForm.goodsIds = this.selectedCoupons.map(coupon => coupon.id).join(',')
      this.hdlUpdate()
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container{
  .disabled {
    ::v-deep{
      .el-input{
        width: 140px;
      }
    }
  }
}
</style>

